<?php
namespace app\tool\controller;

use app\BaseController;
use think\facade\Request;
use think\facade\Log;

class Index extends BaseController
{
    public function index(){
        return view();
    }




    public function sign(){
        $data = Request::post();
        if (!isset($data['merchant_code']) || $data['merchant_code'] == '') {
            return ['code'=>0,'msg'=>'商户编码必填'];
        }
        if (!isset($data['secret']) || $data['secret'] == '') {
            return ['code'=>0,'msg'=>'商户秘钥必填'];
        }
        if (!isset($data['random']) || $data['random'] == '') {
            return ['code'=>0,'msg'=>'随机数必填'];
        }
        if (!isset($data['timestamp']) || $data['timestamp'] == '') {
            return['code'=>0,'msg'=>'时间戳必填'];
        }
        $back_da = array();
        $secret = $data['secret'];
        unset($data['secret']);
        if(isset($data['str'])){
            unset($data['str']);
        }
        if(isset($data['urlcode'])){
            unset($data['urlcode']);
        }
        if(isset($data['sign'])){
            unset($data['sign']);
        }
        //记录参数数据
        Log::write("接收的参数");
        Log::write($data);
        //参数排序
        ksort($data);
        //日志记录数据
        Log::write("参数排序");
        Log::write($data);
        //$p = http_build_query($data);
        //Log::write($p);
        //拼接字符串
        $str = "";
        foreach ($data as $k => $v) {
            if ($str == "") {
                $str = $k . "=" . $v;
            }else{
                $str = $str ."&". $k . "=" . $v;
            }
            
        }
        //参数字符串拼接秘钥
        $str = $str . $secret;
        //日志记录数据
        Log::write("参数字符串拼接秘钥");
        Log::write($str);
        $back_da['code'] = 1;
        $back_da['msg'] = 'SUCCESS';
        $back_da['data']['str'] = $str;
        //将数据进行urlcode编码
        $params = rawurlencode($str);
        //日志记录数据
        Log::write("将数据进行urlcode编码");
        Log::write($params);
        $back_da['data']['urlcode'] = $params;
        //md5加密生成签名
        $sign = md5($params);
        Log::write('签名：'.$sign);
        $back_da['data']['sign'] = $sign;

        return $back_da;
    }
}
